package xyz.hubery.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import xyz.hubery.domain.UserWallet;
import xyz.hubery.model.R;
import xyz.hubery.service.UserWalletService;

import java.util.List;

@RestController
@Api(tags = "用户的提币地址")
@RequestMapping("/userWallets")
public class UserWalletController {
    @Autowired
    private UserWalletService userWalletService ;
    @Autowired
    private UserController userController;

    @GetMapping
    @ApiOperation(value = "分页查询用户的提币地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId" ,value = "用户的 id") ,
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页显示的条数")
    })
    @PreAuthorize("hasAuthority('user_wallet_query')")
    public R<Page<UserWallet>> findByPage(@ApiIgnore Page<UserWallet> page , Long
            userId){
        page.addOrder(OrderItem.desc("last_update_time")) ;
        Page<UserWallet> userWalletPage = userWalletService.page(page ,new LambdaQueryWrapper<UserWallet>().eq(userId!=null,UserWallet::getUserId,userId)) ;
        return R.ok(userWalletPage) ;
    }

    @PostMapping
    @ApiOperation("新增用户的提币地址")
    public R add(@RequestBody @Validated UserWallet userWallet) {
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        userWallet.setUserId(userId);
        boolean b = userWalletService.addUserWallet(userWallet);
        return b ? R.ok(): R.fail("新增失败") ;
    }

    @GetMapping("/getCoinAddress/{coinId}")
    @ApiOperation("查询用户某种币的提现地址")
    public R<List<UserWallet>> getCoinAddress(@PathVariable("coinId") Long coinId) {
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        List<UserWallet>  userWallets = userWalletService.getCoinAddress(userId,coinId);
        return R.ok(userWallets) ;
    }

    @PostMapping("/deleteAddress")
    @ApiOperation("删除用户的提币地址")
    public R delete(@RequestParam("addressId") Long addressId,@RequestParam("payPassword") Long payPassword) {
        boolean b = userWalletService.deleteUserWallet(addressId, payPassword);
        if(!b){
            return R.fail("删除失败") ;
        }
        return R.ok();
    }
}
